package com.adingxiong.cft.service.impl;

import com.adingxiong.cft.entity.Role;
import com.adingxiong.cft.entity.TUser;
import com.adingxiong.cft.entity.UserRole;
import com.adingxiong.cft.entity.dto.UserRoleBo;
import com.adingxiong.cft.errors.Assert;
import com.adingxiong.cft.mapper.RoleMapper;
import com.adingxiong.cft.mapper.TUserMapper;
import com.adingxiong.cft.mapper.UserRoleMapper;
import com.adingxiong.cft.service.IUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户角色关联表 服务实现类
 * </p>
 *
 * @author xiongc
 * @since 2020-09-25
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private TUserMapper userMapper;

    @Override
    public boolean save(UserRoleBo bo) {
        UserRole r = getByParam(bo);
        if( r != null){
            Assert.fail("该用户已经拥有该权限");
        }
        Role role = roleMapper.selectById(bo.getRoleId());
        if(role == null){
            Assert.fail("角色不存在");
        }
        TUser user = userMapper.selectById(bo.getUserId());
        if( user == null){
            Assert.fail("用户不存在");
        }

        UserRole userRole = new UserRole();
        BeanUtils.copyProperties(bo,userRole);
        return save(userRole);
    }

    public UserRole getByParam(UserRoleBo bo){
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<UserRole> lambda = wrapper.lambda();
        lambda.eq(UserRole::getUserId,bo.getUserId());
        lambda.eq(UserRole::getRoleId,bo.getRoleId());
        UserRole roles = getOne(wrapper);
        return roles;
    }

    @Override
    public boolean delByUserId(Integer userId) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserRole::getUserId ,userId);
        return remove(wrapper);
    }
}
